package 网约车;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.*;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class MapTest extends Mapper<LongWritable, Text, Text, Data> {
    Text k = new Text();
    Data v = new Data();
    Map<String, String> address_name = new HashMap<String, String>();

    String ordertime;
    String canceltime;
    String address;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //缓存小表到内存
        URI[] uris = context.getCacheFiles();
        FileSystem fileSystem = FileSystem.get(uris[0], context.getConfiguration());
        FSDataInputStream inputStream = fileSystem.open(new Path(uris[0]));
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = br.readLine()) != null) {
            address_name.put(line.split(",")[0], line.split(",")[1]);
        }
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (value.toString().startsWith("companyid ")) {
            return;
        }
        String[] datas = value.toString().split(",", -1);
        //是否完整
        if (datas.length != 8) {
            return;
        }
        for (String s : datas) {
            if (s == null || s.equals("")) {
                return;
            }
        }
        //判断时间
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            ordertime = sdf2.format(sdf1.parse(datas[3]));
            canceltime = sdf2.format(sdf1.parse(datas[4]));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if ((!ordertime.startsWith("2019-03-07")) && (!canceltime.startsWith("2019-03-07"))) {
            return;
        }
        //将null改成未知
        if ("null".equals(datas[7])) {
            datas[7] = "未知";
        }
        //地区
        if (address_name.containsKey(datas[1])) {
            address = datas[1] + "|" + address_name.get(datas[1]);
        } else {
            address = datas[1] + "|" + "未知";
        }
        k.set(datas[2]);
        v.set(datas[0], address, datas[2], ordertime, canceltime, datas[5], datas[6], datas[7]);
        context.write(k, v);
    }
}
